package com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.segments;

import java.util.Arrays;
import java.util.List;

import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.conditions.ISqlSegment;
import com.gitee.magic.jdbc.persistence.source.jdbc.sqlplus.toolkit.StringPool;

/**
 * <p>
 * 合并 SQL 片段
 * </p>
 *
 * @author Start
 */
public class MergeSegments implements ISqlSegment {

    private final NormalSegmentList normal = new NormalSegmentList();
    private final GroupBySegmentList groupBy = new GroupBySegmentList();
    private final HavingSegmentList having = new HavingSegmentList();
    private final OrderBySegmentList orderBy = new OrderBySegmentList();

    public void add(ISqlSegment... iSqlSegments) {
        List<ISqlSegment> list = Arrays.asList(iSqlSegments);
        ISqlSegment sqlSegment = list.get(0);
        if (MatchSegment.ORDER_BY.match(sqlSegment)) {
            orderBy.addAll(list);
        } else if (MatchSegment.GROUP_BY.match(sqlSegment)) {
            groupBy.addAll(list);
        } else if (MatchSegment.HAVING.match(sqlSegment)) {
            having.addAll(list);
        } else {
            normal.addAll(list);
        }
    }

    @Override
    public String getSqlSegment() {
//        if (normal.isEmpty()) {
//            if (!groupBy.isEmpty() || !orderBy.isEmpty()) {
//                return groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
//            } else {
//                return StringPool.EMPTY;
//            }
//        } else {
//            return normal.getSqlSegment() + groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
//        }
    	return getSqlNormal()+getSqlNormalAfter();
    }
    
    public String getSqlNormal() {
    	if (normal.isEmpty()) {
            return StringPool.EMPTY;
    	}else {
        	return normal.getSqlSegment();
    	}
    }
    
    public String getSqlNormalAfter() {
    	if (normal.isEmpty()) {
            if (!groupBy.isEmpty() || !orderBy.isEmpty()) {
                return groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
            } else {
                return StringPool.EMPTY;
            }
        } else {
            return groupBy.getSqlSegment() + having.getSqlSegment() + orderBy.getSqlSegment();
        }
    }

	public NormalSegmentList getNormal() {
		return normal;
	}
	
	public OrderBySegmentList getOrderBy() {
		return orderBy;
	}

}
